#!/usr/bin/env python3
"""
command line to generate password hash by pbkdf2
"""

import sys
import re
from werkzeug.security import generate_password_hash


def usage():
    """ usage """
    print(
        """usage: generate_password PASSWORD

Requirements:
1. PASSWORD must be within the 'latin1' character set
2. PASSWORD strength require:
    length must be between 6 and 32
    at least 1 digit [0-9]
    at least 1 alphabet [a-z]
    at least 1 alphabet of Upper Case [A-Z]
    at least 1 special character from [~!@#%^*_+=-]
"""
    )


def password_encode_check(password):
    """ check if password within the latin1 character set """
    try:
        password.encode("latin1")
    except UnicodeEncodeError as err:
        return str(err)
    return None


def password_strength_check(password):
    """
    Verify the strength of 'password'
    Returns a dict indicating the wrong criteria
    """

    # calculating the length
    length_error = len(password) < 6 or len(password) > 32

    # searching for digits
    digit_error = re.search(r"\d", password) is None

    # searching for uppercase
    uppercase_error = re.search(r"[A-Z]", password) is None

    # searching for lowercase
    lowercase_error = re.search(r"[a-z]", password) is None

    # searching for symbols
    symbol_error = re.search(r"[~!@#%^*_+=-]", password) is None

    # overall result
    password_ok = not (length_error or digit_error or uppercase_error or lowercase_error or symbol_error)

    return {
        'ok': password_ok,
        'error': {
            'length': length_error,
            'digit': digit_error,
            'uppercase': uppercase_error,
            'lowercase': lowercase_error,
            'symbol': symbol_error,
        }
    }


if __name__ == "__main__":
    if len(sys.argv) != 2:
        usage()
        print("Error: One password input allowed.")
        sys.exit(1)

    password_ = sys.argv[1]

    ret = password_encode_check(password_)
    if ret:
        usage()
        print("PASSWORD: only latin1 character set are allowed")
        sys.exit(1)

    ret = password_strength_check(password_)
    if not ret['ok']:
        usage()
        print("Password strength is not satisfied:")
        for item in ret['error']:
            if ret['error'][item]:
                print("{} not satisfied.".format(item))
        sys.exit(1)
    else:
        print(generate_password_hash(password_))
